<template>
  <div>
    <el-menu
        :default-active="activeIndex"
        class="sign-box-menu"
        mode="horizontal"
        @select="handleSelect"
        style="margin-bottom: 20px"
    >
      <div>
        <el-menu-item index="1" style="font-size: 20px">邮箱注册</el-menu-item>
      </div>

      <div>
        <el-menu-item index="2" style="font-size: 20px">电话注册</el-menu-item>
      </div>
    </el-menu>
    <el-form
        name="ruleForm"
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        class="rule-form"
    >
      <el-form-item
          prop="email"
          class="rule-form-input-item"
          v-if="this.usernameInfo == '请输入邮箱'"
      >
        <div class="rule-form-input-div">
          <el-input
              class="input-item"
              v-model="ruleForm.email"
              :placeholder="this.usernameInfo"
          ></el-input>
        </div>
      </el-form-item>

      <el-form-item prop="phone" class="rule-form-input-item" v-else>
        <div class="rule-form-input-div">
          <el-input
              type="tel"
              class="input-item"
              v-model="ruleForm.phone"
              :placeholder="this.usernameInfo"
          >
          </el-input>
        </div>
      </el-form-item>

      <el-form-item prop="captcha" class="rule-form-input-item">
        <div class="rule-form-input-div">
          <el-input
              class="input-item"
              v-model="ruleForm.captcha"
              style="width: 70%"
              placeholder="请输入收到的验证码，区分大小写"
          ></el-input>
          <el-button
              @click="obtainCaptcha('ruleForm')"
              :loading="false"
              :disabled="state.disabled"
              style="
              margin-left: 13px;
              color: #fff;
              background-color: #ea5947;
              border-color: #ea5947;
            "
              ref="captcha"
          >
            {{ state.getCodeText }}
          </el-button>
        </div>
      </el-form-item>

      <el-form-item prop="password" class="rule-form-input-item">
        <div class="rule-form-input-div">
          <el-input
              type="password"
              placeholder="请输入密码"
              v-model="ruleForm.password"
              autocomplete="off"
          ></el-input>
        </div>
      </el-form-item>
      <el-form-item prop="repassword" class="rule-form-input-item">
        <div class="rule-form-input-div">
          <el-input
              type="password"
              placeholder="请确认密码"
              v-model="ruleForm.repassword"
              autocomplete="off"
          ></el-input>
        </div>
      </el-form-item>

      <el-button
          class="btn"
          type="primary"
          v-loading.fullscreen.lock="fullscreenLoading"
          @click="submitForm('ruleForm')"
      >
        <span v-if="spanIf">下一步</span>
        <span v-else>等待....</span>
      </el-button>
    </el-form>
  </div>
</template>

<script>
import "@/styles/css/background/index-bg.css";
import {reactive} from "vue";
import {captchaGet} from '@/apis/common'
import {captchaCheck} from "@/apis/common";

export default {
  name: 'RegisterFirst',
  inject: ["reload"],
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        // if (this.ruleForm.checkPass !== "") {
        //   this.$refs.ruleForm.validateField("checkPass");
        // }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };

    return {
      fullscreenLoading: false,
      /* 验证码信息 */
      state: reactive({
        // 获取验证码
        getCodeText: "获取验证码",
        disabled: false,
        holdTime: 60, //默认60秒计时
      }),
      spanIf: true,
      usernameInfo: "请输入邮箱",
      activeIndex: "1",
      ruleForm: {
        phone: '',
        email: '',
        captcha: "",
        password: "",
        repassword: "",
      },
      value: '',
      rules: {
        email: [
          {required: true, message: "账号不能为空", trigger: "blur"},
          {type: "email", message: "请输入正确的邮箱地址", trigger: "blur"},
        ],
        phone: [
          {required: true, message: '账号不能为空', trigger: 'blur'},
          {type: "string", trigger: 'blur', len: 11, message: '请输入正确格式的电话号码', pattern: /^1(3|4|5|7|8|9)\d{9}$/},

        ],
        password: [
          {validator: validatePass, trigger: "blur"},

          {
            min: 5,
            max: 8,
            message: "长度在 5 到 8 个任意字符",
            trigger: "blur",
          },
        ],
        repassword: [
          {validator: validatePass2, trigger: "blur"},

          {
            min: 5,
            max: 8,
            message: "长度在 5 到 8 个任意字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.spanIf = true
  },
  methods: {


    // 邮箱注册下一步
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.spanIf = false
          // 检查验证码是否正确
          captchaCheck(this.ruleForm.phone === '' ? this.ruleForm.email : this.ruleForm.phone,
              this.ruleForm.captcha).then((resp) => {
            if (resp?.data?.code == 1) {
              // 时间函数停止1秒
              setTimeout(() => {
                // 路由转换
                this.$router.push({
                  name: 'second',
                  params: {
                    ruleForm: this.ruleForm,
                  },
                }).catch((error) => {
                  console.log(error)
                })

              }, 1000)
            } else {
              this.$message.error(resp?.data?.msg)
            }
          })

        } else {

          return false;
        }
      });


    },


    // 获取验证码
    obtainCaptcha(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.state.disabled = true;
          this.state.getCodeText = "发送中..."; //发送验证码
          // 请求获取验证码
          // 时间函数
          setTimeout(async () => {
            captchaGet(this.ruleForm.phone === '' ? this.ruleForm.email : this.ruleForm.phone).then((resp) => {
              if (resp?.data?.code == 1) {
                this.$message.success("获取到验证码==>" + resp?.data?.data)
              } else {
                this.$message.error(resp?.data?.msg)
              }
            })
            this.setTimer(); //调用定时器方法
          }, 200);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    // 切换页面
    handleSelect(key, keyPath) {
      // 电话邮箱登录页面js切换

      if (key == 1) {
        this.usernameInfo = "请输入邮箱";
      } else if (key == 2) {
        this.usernameInfo = "请输入电话";
      } else {
        this.$message.error("切换页面时出现了异常错误，请稍后重试！！");
      }
    },

    // 计时器
    setTimer() {
      let Timer = null;
      Timer = setInterval(() => {
        if (this.state.holdTime <= 0) {
          this.state.disabled = false;
          this.state.getCodeText = "获取验证码";
          clearInterval(Timer); //清除该函数
          return;
        }
        this.state.getCodeText = "等待(" + this.state.holdTime + ")";
        this.state.holdTime--;
      }, 1000);
    },
  },
};
</script>

<style scoped>
div {
  box-sizing: border-box;
  display: block;
}

.sign-body-header {
  display: block;
}

.rule-form {
  width: 420px;
  margin: 0 auto;
  display: block;
}

.rule-from-input-items {
}

.rule-form-input-item {
  margin-bottom: 22px;
}

.rule-form-input-div {
  line-height: 44px;
  display: inline-block;
  font-size: 14px;
  position: relative;
  width: 100%;
}

.input-item {
  height: 44px;
  line-height: 44px;
  -webkit-appearance: none;
  background-image: none;
  border-radius: 4px;
  box-sizing: border-box;
  display: inline-block;
  outline: 0;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  width: 100%;
}

button,
select {
  text-transform: none;
}

.btn {
  margin-top: 18px;
  width: 100%;
  padding: 14px 20px;
  display: inline-block;
  line-height: 1;
  white-space: nowrap;
  cursor: pointer;
  color: #fff;
  background-color: #ea5947;
  border-color: #ea5947;
  -webkit-appearance: none;
  text-align: center;
  box-sizing: border-box;
  outline: 0;
  transition: 0.1s;
  font-weight: 400;
  -webkit-user-select: none;
  font-size: 14px;
  border-radius: 4px;
  min-width: 88px;
}

span {
  color: #fff;
  line-height: 1;
  font-size: 14px;
}

.login {
  color: #444;
  background-color: transparent;
  text-decoration: none;
}

.sign-box-menu {
  width: 420px;
  margin: 0 auto;
  display: block;
}

.el-menu.el-menu--horizontal {
  border-bottom: none;
}

.sign-box-menu div {
  width: 50%;
  display: block;
  float: left;
  text-align: center;
}

.el-menu-item.is-active {
  color: black;
  border-bottom: 2px solid #f00;
}

.el-menu-item:hover {
  background-color: white;
}
</style>